//
//  BCStarScoreView.m
//  BangcaiBuy
//
//  Created by lsy on 16/6/30.
//  Copyright © 2016年 BCB. All rights reserved.
//

#import "BCStarScoreView.h"

@interface BCStarScoreView ()
@property (nonatomic, weak) CAShapeLayer *backgroudLayer;

@end

@implementation BCStarScoreView
- (void)createView
{
    //使用时, 视图的宽度必须大于高度
    NSAssert(!(self.frame.size.width < self.frame.size.height), @"视图的宽度小于高度!");
    
    self.backgroundColor = [UIColor clearColor];
    NSInteger num =self.frame.size.width / self.frame.size.height;//个数
    
    //底层
    UIBezierPath *backgroudPath = [UIBezierPath bezierPath];
    [backgroudPath moveToPoint:CGPointMake(0, self.frame.size.height * 0.5)];
    [backgroudPath addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height * 0.5)];
    CAShapeLayer *backgroudLayer = [CAShapeLayer layer];
    backgroudLayer.path = backgroudPath.CGPath;
    backgroudLayer.lineWidth = self.frame.size.height;
    [self.layer addSublayer:backgroudLayer];
    self.backgroudLayer = backgroudLayer;
    
    //画图
    UIBezierPath *star = [[UIBezierPath alloc] init];
    for (int i = 1; i < num * 2; i ++) {
        if (i % 2 != 0) {
            CGFloat startX = self.frame.size.width / (self.frame.size.width / self.frame.size.height) * i;
            CGPoint center = CGPointMake(startX * 0.5, self.frame.size.height * 0.5);
            CGFloat radius = self.frame.size.height * 0.5;
            CGFloat angle = 4 * M_PI / 5;
            
            //画五角星
            [star moveToPoint:CGPointMake(startX * 0.5, 0)];
            for (int i = 0; i < 5; i ++) {
                CGFloat x = center.x - sinf((i + 1) * angle) * radius;
                CGFloat y = center.y - cosf((i + 1) * angle) * radius;
                [star addLineToPoint:CGPointMake(x, y)];
            }
            [star addLineToPoint:CGPointMake(startX * 0.5, 0)];
        }
    }
    
    //遮罩
    CAShapeLayer *starLayer = [CAShapeLayer layer];
    starLayer.path = star.CGPath;
    self.layer.mask = starLayer;

}

- (void)setStartColor:(UIColor *)startColor {
    _startColor = startColor;
    self.backgroudLayer.strokeColor = startColor.CGColor;
    self.backgroudLayer.fillColor = startColor.CGColor;
}

- (void)setScore:(CGFloat)score {
    NSInteger num = self.frame.size.width / self.frame.size.height;
    if (score > num * 2) {//设置上限
        score = num * 2;
    }
    _score = score;
    self.backgroudLayer.strokeEnd = score / (num * 2);
}

@end
